#include "Config.h"

Config::Config()
	:Component(COMP_CONFIG),
	m_fullScreen(false),
	m_resMap(""),
	m_screenHeight(0),
	m_screenWidth(0),
	m_vsyncEnable(false)
{
	Initial();
}

Config::~Config()
{
}

void Config::AddedToObject()
{
	RequestMessage(MSG_SAVE_CONFIG,&Config::SaveConfig);
}

bool Config::GetBool(const string& str) const
{
	if(str=="TRUE")
		return true;
	else
		return false;
}

unsigned int Config::GetUINT(const string& str) const
{
	unsigned int tmp=0;
	try
	{
		tmp=boost::lexical_cast<unsigned int>(str);
	}
	catch(boost::bad_lexical_cast &)
	{
		tmp = -1;
	}
	return tmp;
}

string Config::SetBool(bool b)
{
	if(b)
		return "TRUE";
	else
		return "FALSE";
}

string Config::SetUINT(unsigned int ui)
{
	string tmp;
	try
	{
		boost::lexical_cast<string>(ui);
	}
	catch(boost::bad_lexical_cast&)
	{
		tmp="UNKNOWN";
	}
	return tmp;
}

void Config::Initial()
{
	m_configFile.open(CONFIG_FILE_NAME,fstream::in);
	if(!m_configFile.is_open())
	{
		EXCEPTION("Can not load config file")
	}
	m_configFile.seekg(0,ios::beg);
	string name,attr;
	while(ReadNextConfig(name,attr))
	{
		if(name == "[FULL_SCREEN]")
		{
			m_fullScreen = GetBool(attr);
		}
		else if(name == "[VSYNC]")
		{
			m_vsyncEnable = GetBool(attr);
		}
		else if(name == "[WIDTH]")
		{
			m_screenWidth=GetUINT(attr);
		}
		else if(name == "[HEIGHT]")
		{
			m_screenHeight=GetUINT(attr);
		}
		else if(name=="[RES_MAP]")
		{
			m_resMap=attr;
		}
		else if(name.find("CAMERA")!=name.npos)
		{
			m_keyMap[name]=attr;
		}
	}
	m_configFile.close();
}

Config::KeyMap Config::GetKeyControl()
{
	return m_keyMap;
}

bool Config::ReadNextConfig(string& name, string& attr)
{
	string line;
	if(m_configFile.eof())
		return false;

	getline(m_configFile,line);
	size_t found=line.find(" ");
	if(found!=string::npos)
	{
		name=line.substr(0,found);
		attr=line.substr(found+1,line.length());
		return true;
	}
	else
		return false;
}

void Config::SaveConfig(const Message& msg)
{
	m_configFile.open(CONFIG_FILE_NAME,fstream::out|fstream::trunc);
	m_configFile.seekg(0,ios::beg);
	string name,attr;
	
	name="[FULL_SCREEN]";
	attr=SetBool(m_fullScreen);
	m_configFile<<name<<" "<<attr<<endl;
	
	name="[VSYNC]";
	attr=SetBool(m_vsyncEnable);
	m_configFile<<name<<" "<<attr<<endl;
	
	name="[WIDTH]";
	attr=SetUINT(m_screenWidth);
	m_configFile<<name<<" "<<attr<<endl;
	
	name="[HEIGHT]";
	attr=SetUINT(m_screenHeight);
	m_configFile<<name<<" "<<attr<<endl;
	
	name="[RES_MAP]";
	attr=m_resMap;
	m_configFile<<name<<" "<<attr<<endl;

	m_configFile.close();
}